package cn.thornbird.orgsync.util;

import cn.thornbird.orgsync.model.AppUserData;
import org.apache.commons.lang3.StringUtils;

public class UserIdUtil {

    public static String getEmailAccountName(AppUserData user) {
        return PinyinUtil.toPinyin(user.getName()).toLowerCase().replace(" ", "_");
    }

    public static String getUserId(AppUserData user) {
        String userId = toUserId(user.getId());
        if (StringUtils.isEmpty(userId)) {
            userId = toUserId(user.getEmployeeNo());
        }
        if (StringUtils.isEmpty(userId)) {
            userId = toUserId(user.getName());
        }
        return userId;
    }

    public static String toUserId(String text) {
        StringBuilder userId = new StringBuilder();
        if (!StringUtils.isEmpty(text)) {
            for (char c : text.toLowerCase().toCharArray()) {
                if (Character.isLetterOrDigit(c)) {
                    userId.append(c);
                } else if (c == '_' || c == '-' || c == '@') {
                    userId.append(c);
                }
                if (userId.length() >= 64) {
                    break;
                }
            }
        }
        return userId.toString();
    }

}
